package cn.tramy.pinxian.common.util.func

import cn.tramy.pinxian.common.exception.CommonException
import java.util.*

/**
 * Created  on 16/9/10.
 *
 *
 * 如果checkFun满足则抛出exceptionFunc返回的异常
 */
class LoadCheckExceptionFunc<T>(private val loadFunc: () -> T?) : CommonFunc {
    private var checkFunc: ((data: T?) -> Boolean)? = null

    private var exceptionFunc: ((data: T?) -> Throwable)? = null

    fun check(checkFunc: (data: T?) -> Boolean): LoadCheckExceptionFunc<*> {
        this.checkFunc = checkFunc
        return this
    }

    fun ifNull(): LoadCheckExceptionFunc<T> {
        check({ t -> Objects.isNull(t) })
        return this
    }

    fun ifNonNull(): LoadCheckExceptionFunc<T> {
        check({ t -> Objects.nonNull(t) })
        return this
    }


    fun invalidException(): LoadCheckExceptionFunc<T> {
        exception { CommonException.invalidOperation() }
        return this
    }

    fun nameDuplicatedException(name: String): LoadCheckExceptionFunc<T> {
        exception { CommonException.nameDuplicatedException(name) }
        return this
    }


    fun codeDuplicatedException(code: String): LoadCheckExceptionFunc<T> {
        exception { CommonException.codeDuplicatedException(code) }
        return this
    }

    fun parameterError(): LoadCheckExceptionFunc<T> {
        exception { CommonException.invalidOperation() }
        return this
    }


    fun exception(exceptionFunc: (data: T?) -> Throwable): LoadCheckExceptionFunc<*> {
        this.exceptionFunc = exceptionFunc
        return this
    }

    override fun execute() {
        val obj = this.loadFunc()

        checkFunc?.also { if (it(obj)) exceptionFunc?.let { throw it(obj) } }


    }
}
